import { useQuery } from "@tanstack/react-query";
import { useCallback, useEffect, useRef } from "react";
import { useAtom, useAtomValue, useSetAtom } from "jotai";
import { useLatestRef, useSearchParam } from "shared/hooks";
import { API_BASE_URL, defaultUri } from "./lib/constants";
import useCompletion from "./lib/hooks/useCompletion";
import { customPromptAtom, isUseCustomPromptAtom } from "@/store/customPrompt";
// import CustomPrompt from "@/components/CustomPrompt";
import LoadingIcon from "@/assets/icons/loading.svg?jsx";
import { request } from "shared/requests";
import { Year } from "@/lib/types";
import { allYearsAtom, selectYearAtom } from "@/store/years";
import { selectModelAtom } from "@/store/model";
import event from "./lib/event";
import HorizontalTime from "./components/HorizontalTime";
import TimeController from "./components/TimeController";
import ToolBar from "./components/Toolbar";
import TimelineView from "@/components/TimelineView";
import CategoryView from "@/components/CategoryView";
import { viewModelAtom } from "./store/viewModel";
import { eventsAtom, sortedEventsAtom } from "./store/events";

export default function Home() {
  const model = useAtomValue(selectModelAtom);
  const [year, setYear] = useAtom(selectYearAtom);
  const isUseCustomPrompt = useAtomValue(isUseCustomPromptAtom);
  const customPrompt = useAtomValue(customPromptAtom);
  const setAllYears = useSetAtom(allYearsAtom);
  const viewModel = useAtomValue(viewModelAtom);
  const setEvents = useSetAtom(eventsAtom);
  const events = useAtomValue(sortedEventsAtom);

  const uri = useSearchParam("uri", defaultUri);

  const { data: years, isSuccess } = useQuery({
    queryKey: ["years", uri],
    queryFn: () => request<Year[]>(`${API_BASE_URL}/years?uri=${uri}`),
    staleTime: Infinity,
  });

  const { handleCompletion, retry, isLoading, chunks, error, params } =
    useCompletion();

  useEffect(() => {
    setEvents(chunks);
  }, [chunks]);

  useEffect(() => {
    if (isSuccess) {
      setYear(years[0].raw);
      setAllYears(years);
    }
  }, [isSuccess, years, setAllYears, setYear]);

  const go = useCallback(() => {
    if (!uri || !model || !year) {
      console.warn("缺失必要参数");
      return;
    }
    handleCompletion(
      Object.assign(
        { uri, model, year },
        isUseCustomPrompt && { question: customPrompt },
      ),
    );
  }, [handleCompletion, uri, model, year, isUseCustomPrompt, customPrompt]);

  const goRef = useLatestRef(go);

  useEffect(() => {
    goRef.current();
  }, [year, goRef]);

  useEffect(() => {
    function reload() {
      goRef.current();
    }
    event.on("load", reload);
    return () => {
      event.off("load", reload);
    };
  }, [goRef]);

  return (
    <>
      <HorizontalTime />
      <ToolBar />
      <div className="p-4">
        {/* <CustomPrompt /> */}
        <TimeController queryYear={params.year} />
        {error && (
          <div className="my-4">
            <div className="rounded border border-red-500 bg-red-100 p-4">
              <p>Generate Error</p>
            </div>
            <button
              className="mx-auto mt-4 block rounded bg-red-500 px-4 py-2 text-white"
              onClick={retry}
            >
              Retry
            </button>
          </div>
        )}
        {events.length === 0 && isLoading && (
          <div className="flex justify-center py-8">
            <LoadingIcon height={30} width={30} />
          </div>
        )}
        {events.length > 0 && (
          <div className="py-8">
            {viewModel === "timeline" ? (
              <TimelineView events={events} />
            ) : (
              <CategoryView events={events} />
            )}
          </div>
        )}
      </div>
    </>
  );
}
